package com.linko.intelligent.remote.core.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.linko.intelligent.common.util.HttpUtil;
import com.linko.intelligent.remote.core.mapper.BaseIotDeviceMapper;
import com.linko.intelligent.remote.core.mapper.DeviceInfoMapper;
import com.linko.intelligent.remote.core.service.DeviceInfoRefreshService;
import com.linko.intelligent.remote.pojo.dto.BaseIotDeviceDto;
import com.linko.intelligent.remote.pojo.dto.DeviceInfoDto;
import com.linko.intelligent.remote.pojo.po.BaseIotDevice;
import com.linko.intelligent.remote.pojo.po.DeviceInfo;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DeviceInfoRefreshServiceImpl implements DeviceInfoRefreshService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceInfoRefreshServiceImpl.class);

    @Value("${url.dj92}")
    private String apiUrl;

    @Value("${url.authorization}")
    private String authorization;

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private BaseIotDeviceMapper baseIotDeviceMapper;

    public void refresh() {
        // 获取请求头
        HashMap<String, String> requestHeader = new HashMap<>();
        requestHeader.put("Authorization", authorization);

        // 发送 POST 请求并获取响应
        try (Response response = HttpUtil.get(apiUrl + "/data/deviceInfo/list", requestHeader)) {
            // 处理响应
            if (response.isSuccessful()) {
                handleResponse(response);
            } else {
                logger.error("请求失败，HTTP状态码：{}", response.code());
            }
        } catch (IOException e) {
            logger.error("请求失败: {}", e.getMessage());
        }
    }

    private void handleResponse(Response response) throws IOException {
        String responseBody = response.body().string();
        JSONObject jsonResponse = JSONObject.parseObject(responseBody);
        JSONArray listArray = jsonResponse.getJSONArray("data");

        // 解析并处理响应数据
        List<DeviceInfoDto> deviceInfoDtoList = parseAndProcessResponse(listArray);

        // 记录成功信息
        logger.info("成功解析并处理响应数据");
    }

    private List<DeviceInfoDto> parseAndProcessResponse(JSONArray listArray) {
        // 创建列表存储设备信息
        List<DeviceInfoDto> deviceInfoDtoList = new ArrayList<>();
        for (int i = 0; i < listArray.size(); i++) {
            JSONObject jsonObject = listArray.getJSONObject(i);
            // 将 JSON 对象转换为 DeviceInfoDto 对象
            DeviceInfoDto deviceInfoDto = jsonObject.toJavaObject(DeviceInfoDto.class);
            deviceInfoDtoList.add(deviceInfoDto);
        }

        // 清空现有数据
        deviceInfoMapper.deleteAll();

        // 插入新数据
        List<DeviceInfo> deviceInfoList = new ArrayList<>();
        List<BaseIotDevice> baseIotDeviceList = new ArrayList<>();

        for (DeviceInfoDto dto : deviceInfoDtoList) {
            DeviceInfo deviceInfo = new DeviceInfo();
            BeanUtils.copyProperties(dto, deviceInfo);
            deviceInfoList.add(deviceInfo);

            for (BaseIotDeviceDto bindDto : dto.getBindList()) {
                BaseIotDevice bind = new BaseIotDevice();
                BeanUtils.copyProperties(bindDto, bind);
                baseIotDeviceList.add(bind);
            }
        }

        deviceInfoMapper.batchInsert(deviceInfoList);

        baseIotDeviceMapper.deleteAll();
        baseIotDeviceMapper.batchInsert(baseIotDeviceList);

        return deviceInfoDtoList;
    }
}
